/*
 Licensed to the Apache Software Foundation (ASF) under one or more
 contributor license agreements.  See the NOTICE file distributed with
 this work for additional information regarding copyright ownership.
 The ASF licenses this file to You under the Apache License, Version 2.0
 (the "License"); you may not use this file except in compliance with
 the License.  You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
*/

// #/:core/files
sammy.get
(
  new RegExp( app.core_regex_base + '\\/(files)$' ),
  function( context )
  {
    core_basepath = this.active_core.attr( 'data-basepath' );
    current_core = context.params.splat[0];

    var content_element = $( '#content' );

    var file_endpoint = core_basepath + '/admin/file';

    var path = context.path.split( '?' );
    var selected_file = null;
    if( path && path[1] )
    {
      selected_file = path[1].split( '=' ).pop();
    }

    $.get
    (
      'tpl/files.html',
      function( template )
      {
        content_element
          .html( template );

        var frame_element = $( '#frame', content_element );

        var tree_callback = function( event, data )
        {
          $( 'li[data-file].jstree-closed', event.currentTarget )
            .filter
            (
              function( index, element )
              {
                return selected_file && 0 === selected_file.indexOf( $( element ).data( 'file' ) );
              }
            )
            .each
            (
              function( index, element )
              {
                data.inst.open_node( element );
              }
            );

          if( selected_file )
          {
            $( 'li[data-file="' + selected_file.replace( /\/$/, '' ) + '"] > a', event.currentTarget )
              .addClass( 'active' );
          }
        };
        
        //绑定编辑
        $('#editFileBtn', frame_element).bind("click", function(){
        	alertEditBox();
        });
        
        //弹出 编辑框
        function alertEditBox(collection, path, fileContent){
        	
        	var collection = $("#fileHideContent").attr("collection");
        	var path = $("#fileHideContent").attr("path");
        	var contentType = $("#fileHideContent").attr("contentType");
        	var oldFileContent = $("#fileHideContent").val();
        	
        	var isCloud = $('#cloud.global').is(':visible');
        	var appendConfNameInput = "";
        	if(isCloud){
        		appendConfNameInput = "<input id='property-returnValue-confName' type='text' maxlength='50' style='width: 250px;' placeholder='请输入zk对应的配置名,默认为集合名'/><br><br>";
        	}
        	
    		var d = dialog({
    			title: '编辑文件（请谨慎修改）',
    			content: appendConfNameInput+'<textarea id="property-returnValue-fileContent" style="width: 100%;height: 90%;overflow: scroll;">'+oldFileContent+'</textarea>',
    			okValue: '保存',
    			ok: function () {
    				var fileContent = $('#property-returnValue-fileContent').val();
    				var confName = $('#property-returnValue-confName').val();
    				if(fileContent == null || fileContent == ""){
    					popupMessage("输入内容不能为空！");
    					return false;
    				}
    				
    				var url = app.config.solr_path + '/custom?action=edit_conf&wt=json'
    				var params = {"collection": collection, "path": path, "contentType": contentType, "model": (isCloud?'cloud':'single'), "fileContent": fileContent, "confName": confName};
 
    				$.ajax({
    					url: url, 
    					type: 'POST',
    					dataType: 'json',
    					data: params,
    					success: function(data){
    						popupMessage('编辑文件成功！');
							setTimeout(function(){
								window.location.reload();
							}, 2000);
    					},
    					error: function (xhr, status, e) {
    						var response = eval( 'response = ' + xhr.responseText + ';' );
    						popupMessage(response.error.msg, "error");
    			        }
    				});
    				/*$.post(url, params, function(data){
    					var resp = data.responseHeader;
						var status = resp.status;
						if(status != 0){
							
						}else{
							
						}
					}, "json");*/
    				this.remove();
    			}
    		}).width(750).height(480);
    		d.show();
    	}
      
    	
        var load_tree = function()
        {
          $( '#tree', frame_element )
            .empty()
            .jstree
            (
              {
                plugins : [ 'json_data', 'sort' ],
                json_data : {
                  ajax: {
                    url : file_endpoint + '?wt=json',
                    data : function( n )
                    {
                      if( -1 === n )
                        return null;

                      return {
                        file : n.attr( 'data-file' )
                      };
                    },
                    success : function( response, status, xhr )
                    {
                      var files = [];

                      for( var file in response.files )
                      {
                        var is_directory = response.files[file].directory;
                        var prefix = xhr.data ? xhr.data.file + '/' : ''

                        var item = {
                          data: {
                            title : file,
                            attr : {
                              href : '#/' + current_core + '/files?file=' + prefix + file
                            }
                          },
                          attr : {
                            'data-file' : prefix + file
                          }
                        };

                        if( is_directory )
                        {
                          item.state = 'closed';
                          item.data.attr.href += '/';
                        }

                        files.push( item );
                      }

                      return files;
                    }
                  },
                  progressive_render : true
                },
                core : {
                  animation : 0
                }
              }
            )
            .on
            (
              'loaded.jstree',
              tree_callback
            )
            .on
            (
              'open_node.jstree',
              tree_callback
            );
        };
        load_tree();

        if( selected_file )
        {
          $( '#new-file-holder input' )
            .val
            (
              '/' !== selected_file.substr( -1 )
              ? selected_file.replace( /[^\/]+$/, '' )
              : selected_file
            );
        }

        if( selected_file && '/' !== selected_file.substr( -1 ) )
        {
          frame_element
            .addClass( 'show' );

          var endpoint = file_endpoint + '?file=' + selected_file;

          var content_type_map = { xml : 'text/xml', html : 'text/html', js : 'text/javascript' };
          var file_ext = selected_file.match( /\.(\w+)$/  );
          var contentType = ( content_type_map[ file_ext[1] || '' ] || 'text/plain' )+ ';charset=utf-8';
          endpoint += '&contentType=' + contentType ;

          var public_url = window.location.protocol + '//' + window.location.host + endpoint;

          $( '#url', frame_element )
            .text( public_url )
            .attr( 'href', public_url );

          var load_file = function( load_tree )
          {
            if( load_tree )
            {
              load_tree();
            }

            $.ajax
            (
              {
                url : endpoint,
                context : frame_element,
                beforeSend : function( xhr, settings )
                {
                  var block = $( '.view-file .response', this );

                  if( !block.data( 'placeholder' ) )
                  {
                    block.data( 'placeholder', block.text() );
                  }

                  block
                    .text( block.data( 'placeholder' ) );
                },
                success : function( response, text_status, xhr )
                {
                	
                   try{
                	   //将文件内容设值到文本域
                       var subArray = file_endpoint.split("/");
                       $("#fileHideContent", this).attr("collection", subArray[subArray.length-3]).attr("path", selected_file);
                       $("#fileHideContent", this).attr("contentType", contentType).val(xhr.responseText);
                   }catch(err){
                	  console.log("fileHideContent set fail."+err);
                   }
                  
                  var content_type = xhr.getResponseHeader( 'Content-Type' ) || '';
                  var highlight = null;

                  if( 0 === content_type.indexOf( 'text/xml' ) ||  0 === xhr.responseText.indexOf( '<?xml' ) ||
                      0 === content_type.indexOf( 'text/html' ) ||  0 === xhr.responseText.indexOf( '<!--' ) )
                  {
                    highlight = 'xml';
                  }
                  else if( 0 === content_type.indexOf( 'text/javascript' ) )
                  {
                    highlight = 'javascript';
                  }

                  var code = $(
                    '<pre class="syntax' + ( highlight ? ' language-' + highlight : '' )+ '"><code>' +
                    xhr.responseText.esc() +
                    '</code></pre>'
                  );
                  $( '.view-file .response', this )
                    .html( code );

                  if( highlight )
                  {
                    hljs.highlightBlock( code.get( 0 ) );
                  }

                  $( 'form textarea', this )
                    .val( xhr.responseText );
                },
                error : function( xhr, text_status, error_thrown)
                {
                  $( '.view-file .response', this )
                    .text( 'No such file exists.' );
                },
                complete : function( xhr, text_status )
                {
                }
              }
            );
          }
          load_file();
        }
      }
    );
  }
);

// legacy redirect for 'config' & 'schema' pages
// #/:core/schema, #/:core/config
sammy.get
(
  new RegExp( app.core_regex_base + '\\/(schema|config)$' ),
  function( context )
  {
    context.redirect( '#/' + context.params.splat[0] + '/files?file=' + this.active_core.attr( context.params.splat[1] ) );    
  }
);